package com.ease.core.managers {
   import com.ease.util.MixedUtil;
   import com.ease.util.MruCache;
   import com.ease.util.ReflectionUtil;
   import com.ease.framework.workbench.IPerspectiveFactory;

   import flash.events.Event;
   import flash.events.EventDispatcher;
   import flash.utils.Dictionary;

   import mx.collections.ArrayCollection;

	public class PerspectiveManager extends EventDispatcher {
		private static const SHARED_OBJECT_PERSPECTIVES:String = "shared_object_perspectives";

      private var _perspectiveCache:MruCache = new MruCache(120);
      private var _perspectiveDefineCache:MruCache = new MruCache(120);

      private static var _instance:PerspectiveManager = null;
      public static function getInstance():PerspectiveManager {
         if (!_instance) {
            _instance = new PerspectiveManager();
         }
         return _instance;
      }

		public function PerspectiveManager() {
         if (_instance) {
            throw new Error('PerspectiveManager is singleton');
         }
			loadSharedObjectPerspectives();
		}

		public function loadSharedObjectPerspectives():void {
		}

      public function addPerspectiveDefine(perspectiveId:String, perspectiveType:String):void {
         _perspectiveDefineCache.add(perspectiveId, perspectiveType);
      }

      public function addPerspective(id:String, value:Object):void {
         _perspectiveCache.add(id, value);
      }

      public function getPerspective(perspectiveId:String):* {
         return _perspectiveCache.getValue(perspectiveId);
      }

      public function getPerspectiveLayout(perspectiveId:String):* {
         var perspective:* = _perspectiveCache.getValue(perspectiveId);
         if (perspective == null) {
            var perspectiveType:String = _perspectiveDefineCache.getValue(perspectiveId);
            var perspectiveFactory:IPerspectiveFactory =
               ReflectionUtil.newInstance(perspectiveType, null) as IPerspectiveFactory;
            perspective = perspectiveFactory.layoutDescripter;
            addPerspective(perspective.@id, perspective);
         }
         return perspective;
      }

      public function getActivePerspective():* {
         return getPerspective(activePerspective);
      }

      private var _activePerspective:String;
      [Bindable("activePerspectiveChange")]
      public function get activePerspective():String {
         return _activePerspective;
      }

      public function set activePerspective(value:String):void {
         _activePerspective = value;
         dispatchEvent(new Event("activePerspectiveChange"));
      }

		public function get perspectiveIds():Array {
			return _perspectiveDefineCache.keys;
		}
      
      public function clear():void {
         _perspectiveCache.removeAll();
         _perspectiveDefineCache.removeAll();
      }
	}
}